package com.zfei.gfb.controller;


import cn.hutool.core.date.DateUtil;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Page;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbHouseApplyMapper;
import com.zfei.gfb.dao.GfbHouseMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbGuest;
import com.zfei.gfb.model.GfbHouse;
import com.zfei.gfb.model.GfbHouseApply;
import com.zfei.gfb.model.GfbVillager;
import com.zfei.gfb.request.GfbHouseApplyRequest;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.util.gson.Types;
import com.zfei.gfb.vo.GfbHouseApplyListVo;
import com.zfei.gfb.vo.GfbHouseApplyVo;
import com.zfei.gfb.vo.GfbHouseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author fgh
 * @version 1.0
 */

@Api(tags = "H5房屋预约接口")
@RestController
@RequestMapping("/h5/houseApply")
public class H5HouseApplyController {

    private static final Logger logger = LoggerFactory.getLogger(H5HouseApplyController.class);

    @Resource
    private GfbHouseMapper gfbHouseMapper;

    @Resource
    private GfbHouseApplyMapper gfbHouseApplyMapper;

    @Resource
    private HttpSession httpSession;

    @Auth(type = {Const.VILLAGER, Const.GUEST})
    @ApiOperation(value = "立即预约2-1-1-1")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbHouseApplyVo.class),
    })
    @LogResult
    @HttpJson("/add")
    public Object add(@RequestBody GfbHouseApplyRequest request) {

        request.checkInsertNull();

        GfbHouse house = gfbHouseMapper.selectByPrimaryKey(request.getHouseId());

        if (house.getPutonStatus() == Const.STATUS_OFF) {
            throw new StatusException(Status.INVALID_ARGUMENT, "房屋已下架，无法预约");
        }
        if (house.getStatus() == Const.HOUSE_STATUS_OFF) {
            throw new StatusException(Status.INVALID_ARGUMENT, "房屋审核不通过，无法预约");
        }

        GfbHouseApply record = Beans.copy(request, GfbHouseApply.class);

        Integer id = null;
        Integer type = null;

        if (httpSession.getAttribute(AppContext.SESSION_H5_GUEST) != null) {
            GfbGuest guest = (GfbGuest) httpSession.getAttribute(AppContext.SESSION_H5_GUEST);
            id = guest.getId();
            type = Const.GUEST;
        }
        Object villagerObj = httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);
        if (villagerObj != null) {
            GfbVillager villager = (GfbVillager) villagerObj;
            id = villager.getId();
            if (id.equals(house.getUserId())) {
                throw new StatusException(Status.NOT_ALLOWED, "不能预约自己的房屋");
            }
            type = Const.VILLAGER;
        }
        int size = gfbHouseApplyMapper.selectByHouseIdAndUserIdAndType(house.getId(), id, type).size();
        if (size > 0) {
            throw new StatusException(Status.NOT_ALLOWED, "请勿重复预约");
        }

        record.setUserId(id);
        record.setUserType(type);
        record.setStatus(Const.STATUS_ON);
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());

        gfbHouseApplyMapper.insertSelective(record);

        GfbHouseApplyVo vo = Beans.copy(record, GfbHouseApplyVo.class);
        return vo;
    }

    @Auth(type = {Const.VILLAGER, Const.GUEST})
    @ApiOperation(value = "我预约的房屋3-2-10/3-1-4")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbHouseApplyListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody Page page) {
        page.build(Now::millis);

        Integer id = AppContext.getInstance().getUid();
        Integer type = AppContext.getInstance().getType();

        GfbHouseApplyListVo result = new GfbHouseApplyListVo();
        List<GfbHouseApply> records = gfbHouseApplyMapper.selectByUserIdAndUserType(id, type, page.getOffset(), page.getLimit());
        if (records.isEmpty()) {
            result.setData(new ArrayList<>());
            return result;
        }
        Set<Integer> houseSet = records.stream().map(GfbHouseApply::getHouseId).collect(Collectors.toSet());

        List<GfbHouse> gfbHouses = gfbHouseMapper.selectByIds(houseSet);
        Map<Integer, GfbHouse> houseMap = gfbHouses.stream().collect(Collectors.toMap(GfbHouse::getId, Function.identity()));

        List<GfbHouseApplyVo> gfbHouseApplyVos = Beans.copys(records, GfbHouseApplyVo.class);
        gfbHouseApplyVos.forEach(item -> {
            GfbHouse house = houseMap.get(item.getHouseId());
            GfbHouseVo vo = Beans.copy(house, GfbHouseVo.class);

            vo.setImages(Gsons.fromJson(house.getImages(), Types.StringListType));
            item.setGfbHouseVo(vo);
//            item.setAddress(house.getAddress());
//            item.setPrice(house.getPrice());
//            item.setName(house.getName());
        });


        result.setData(gfbHouseApplyVos);
        return result;
    }


}
